package com.cetcs.kmga.dataManager.util;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.StringTokenizer;

/**
 * ip移位工具类
 *
 * @author xutao
 * @version V1.0 创建时间：2017-09-22 11:20
 *          Copyright 2017 by CETC
 */
public class IpUtil {

    public static String getLongIpToString(Long ipLong) {
        if (ipLong == null || ipLong == 0) return null;
        StringBuilder sb = new StringBuilder();
        sb.append(ipLong >>> 24);
        sb.append('.');
        sb.append(String.valueOf((ipLong & 0x00FFFFFF) >>> 16));
        sb.append('.');
        sb.append(String.valueOf((ipLong & 0x0000FFFF) >>> 8));
        sb.append('.');
        sb.append(String.valueOf(ipLong & 0x000000FF));
        return sb.toString();
    }


    public static Long getStringIpToLong(String ipString) {
        if (ipString == null || ipString.isEmpty()) return 0L;
        long result = 0L;
        StringTokenizer token = new StringTokenizer(ipString, ".");
        result += Long.parseLong(token.nextToken()) << 24;
        result += Long.parseLong(token.nextToken()) << 16;
        result += Long.parseLong(token.nextToken()) << 8;
        result += Long.parseLong(token.nextToken());
        return result;
    }

    /**
     * 通过request 获得ip地址
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = "0.0.0.0";
        //ipAddress = this.getRequest().getRemoteAddr();
        if(request != null) {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                    //根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }

            }

            //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) { //"***.***.***.***".length() = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        }
        return ipAddress;
    }

}
